<template>
  <div
    class="fm-widget-view"
    v-if="element && element.key"
    :class="{ active: selectWidget.key == element.key }"
    :label="element.name"
    @click.stop="handleSelectWidget(index)"
  >
    <template v-if="element.type == 'smallPage'">
      <CardContainer :data="data" :element="element" />
    </template>

    <div class="fm-widget-view-action" v-if="selectWidget.key == element.key">
      <span :title="$t('m.portalDesign.description.she-zhi')" @click.stop="handleWidgetOpensSet(index)"><ych-icon type="setting" /></span>
      <span :title="$t('m.portalDesign.description.tuo-dong-xiao-ye')"> <ych-icon type="drag" /></span>
      <span :title="$t('m.portalDesign.description.fu-zhi-xiao-ye')" @click.stop="handleWidgetClone(index)"><ych-icon type="copy" /></span>
      <span :title="$t('m.portalDesign.description.shan-chu-xiao-ye')" @click.stop="handleWidgetDelete(index)"><ych-icon type="delete" /></span>
    </div>
  </div>
</template>

<script>
import CardContainer from './CardContainer';

export default {
  props: ['element', 'select', 'index', 'data', 'layout'],
  components: {
    // FmUpload,
    CardContainer
  },
  data() {
    return {
      selectWidget: this.select
    };
  },
  mounted() {},
  methods: {
    handleSelectWidget(index) {
      this.selectWidget = this.data.list[index];
    },
    handleWidgetOpensSet() {
      this.$emit('handleWidgetOpensSet');
    },
    handleWidgetDelete(index) {
      if (this.data.list.length - 1 === index) {
        if (index === 0) {
          this.selectWidget = {};
        } else {
          this.selectWidget = this.data.list[index - 1];
        }
      } else {
        this.selectWidget = this.data.list[index + 1];
      }

      this.$nextTick(() => {
        this.data.list.splice(index, 1);
      });
    },
    handleWidgetClone(index) {
      let cloneData = {
        ...this.data.list[index],
        options: { ...this.data.list[index].options },
        key: Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999),
        i: this.data.list.length + ''
      };

      if (
        this.data.list[index].type === 'radio' ||
        this.data.list[index].type === 'checkbox' ||
        this.data.list[index].type === 'select'
      ) {
        cloneData = {
          ...cloneData,
          options: {
            ...cloneData.options,
            options: cloneData.options.options.map(item => ({ ...item }))
          }
        };
      }

      this.data.list.splice(index, 0, cloneData);

      this.$nextTick(() => {
        this.selectWidget = this.data.list[index + 1];
      });
    }
  },
  watch: {
    select(val) {
      this.selectWidget = val;
    },
    selectWidget: {
      handler(val) {
        this.$emit('update:select', val);
      },
      deep: true
    }
  }
};
</script>
